﻿using System;
using System.Web;
using System.Web.Hosting;
using EPiServer;
using EPiServer.Core;
using EPiServer.Web;
using EPiServer.Web.Hosting;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Hosting
{
    /// <summary>
    /// Provides features for managing page folders and files
    /// </summary>
    public static class PageFiles
    {
        /// <summary>
        /// Gets the page files directory for the page, or optionally creates it if it doesn't exist
        /// </summary>
        /// <param name="pageId">ID of the page</param>
        /// <param name="createIfNotExists">Creates the page folder if it doesn't exist</param>
        /// <param name="bypassAccessCheck">If true the directory will be created regardless of current user's access rights</param>
        /// <returns></returns>
        [Obsolete("Use the GetPageDirectory() extension method for PageData objects instead", false)]
        public static UnifiedDirectory GetPageDirectory(int pageId, bool createIfNotExists, bool bypassAccessCheck)
        {
            return DataFactory.Instance.GetPage(new PageReference(pageId)).GetPageDirectory(createIfNotExists, bypassAccessCheck);
        }

        /// <summary>
        /// Gets the page files directory for the page, or optionally creates it if it doesn't exist
        /// </summary>
        /// <param name="page"></param>
        /// <param name="createIfNotExists">Creates the page folder if it doesn't exist</param>
        /// <param name="bypassAccessCheck">If true the directory will be created regardless of current user's access rights</param>
        /// <returns></returns>
        public static UnifiedDirectory GetPageDirectory(this PageData page, bool createIfNotExists, bool bypassAccessCheck)
        {
            if(!bypassAccessCheck)
            {
                return page.GetPageDirectory(createIfNotExists);
            }

            // Get the page folder ID 
            int folderId = (int)page.Property["PageFolderID"].Value;

            // Get the root directory for page files
            string rootFolderPath = VirtualPathHandler.PageDirectoryRootVirtualPath;

            // Get the virtual path to the 
            string pageFolderPath = VirtualPathUtilityEx.Combine(rootFolderPath, VirtualPathUtility.AppendTrailingSlash(folderId.ToString()));

            // Get the page folder
            var pageFolder = HostingEnvironment.VirtualPathProvider.GetDirectory(pageFolderPath) as UnifiedDirectory;

            if (pageFolder==null) // Check if folder exists
            {
                if(createIfNotExists)
                {
                    var rootFolder = HostingEnvironment.VirtualPathProvider.GetDirectory(rootFolderPath) as UnifiedDirectory;

                    if(rootFolder==null)
                    {
                        throw new TemplateFoundationException(string.Format("The PageFiles root folder doesn't exist at '{0}'",rootFolderPath));
                    }

                    // Bypass access check for the root PageFiles folder so we can create the page folder
                    rootFolder.BypassAccessCheck = true;

                    // Create page folder
                    pageFolder = rootFolder.CreateSubdirectory(folderId.ToString());

                    // Since 'bypassAccessCheck' is set to true for this operation
                    pageFolder.BypassAccessCheck = true;
                }
            }
            else
            {
                // Since 'bypassAccessCheck' is set to true for this operation
                pageFolder.BypassAccessCheck = true;
            }

            return pageFolder;
        }
    }
}
